<template>
  <div class="flower-container">
    <div style="display: flex">
      <el-input v-model="name"></el-input>
      <el-button type="primary" @click="getflowers">搜索</el-button>
    </div>

    <el-row :gutter="24">
      <el-col :span="8" v-for="flower in flowers" :key="flower.name">
        <el-card class="box-card">
          <el-image
            style="width: 100%; height: 200px"
            :src="flower.url"
            fit="contain"
            :alt="flower.name"
          ></el-image>
          <h2>{{ flower.name }}</h2>
          <p><strong>价格：</strong>{{ flower.price }}</p>
          <p><strong>介绍：</strong>{{ flower.description }}</p>
          <p><strong>养护要点：</strong>{{ flower.feed }}</p>
          <p><strong>类型：</strong>{{ flower.typeName }}</p>
          <p><strong>库存量：</strong>{{ flower.storeCount }}</p>
          <!-- 数量选择器 -->
          <el-input-number
            v-model="flower.quantity"
            :min="1"
            :max="flower.storeCount"
            label="数量"
          ></el-input-number>
          <!-- 加入购物车按钮 -->
          <el-button type="primary" @click.stop="addToCart(flower)"
            >加入购物车</el-button
          >
          <el-button type="primary" @click="goDetail(flower)"
            >查看详情</el-button
          >
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import { ref } from "vue";
import * as flowerapi from "@/api/flower";
import * as cartapi from "@/api/cart";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const store = useStore();
// 带有数量字段的示例花卉数据
const flowers = ref([
  // 更多花卉数据...
]);
const name = ref("");
const getflowers = async () => {
  const search = name.value ? { name: name.value } : {};
  const { data } = await flowerapi.getAllList(search);
  flowers.value = data.map((i) => ({
    ...i,
    quantity: 1,
  }));
};
getflowers();
// 加入购物车方法
const addToCart = async (flower) => {
  await cartapi.addItem({
    flowerId: flower.flowerId,
    userId: store.state.userInfo.userId,
    count: flower.quantity,
  });
  ElMessage.success("添加成功");
};
const goDetail = (flower) => {
  router.push({
    path: "/user/detail",
    query: flower,
  });
};
</script>

<style scoped>
.box-card {
  margin: 20px 0;
}
.flower-container {
  padding: 20px;
}
</style>